package com.g2.admin.utils;

import java.lang.reflect.Field;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class SecretUtil {
    /**
     * 获取随机数
     *
     * @param len
     * @return
     */
    public static String getRandomStr(int len) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789~!@#$%&*";
        SecureRandom random = new SecureRandom();
        //指定字符串长度，拼接字符并toString
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < len; i++) {
            sb.append(str.charAt(random.nextInt(str.length())));
        }
        return sb.toString();
    }

    /**
     * 获取加密后的密码
     *
     * @param pwd
     * @param slat
     * @return
     */
    public static String encryptPwd(String pwd, String slat) {
        return md5(pwd + slat);
    }

    /**
     * 对字符串md5加密
     *
     * @param str
     * @return
     */
    public static String md5(String str) {
        try {
            // 生成一个MD5加密计算摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 计算md5函数
            md.update(str.getBytes());
            // digest()最后确定返回md5 hash值，返回值为8为字符串。因为md5 hash值是16位的hex值，实际上就是8位的字符
            // BigInteger函数则将8位的字符串转换成16位hex值，用字符串来表示；得到字符串形式的hash值
            return new BigInteger(1, md.digest()).toString(16);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static boolean verifySign(Object object, String secretKey, String sign) {
        return getSign(object, secretKey).equals(sign);
    }

    public static String getSign(Object object, String secretKey) {
        try {
            Map map = new HashMap();
            StringBuffer strBuffer = new StringBuffer();
            if (object instanceof Map) {
                if (((Map) object).isEmpty()) {
                    return "";
                }
                map = (Map) object;
            } else {
                for (Field field : object.getClass().getDeclaredFields()) {
                    field.setAccessible(true);
                    map.put(field.getName(), field.get(object));
                }
            }
            TreeMap<String, String> treeMap = new TreeMap<>(map);
            treeMap.entrySet().forEach(i -> {
                if (i.getValue() == null) {
                    return;
                }
                strBuffer.append(i.getKey()).append("=").append(String.valueOf(i.getValue())).append("&");
            });
            strBuffer.append("key=").append(secretKey);
            return md5(strBuffer.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
